import { getToken } from '@/utils/storageUtils.js'
import store from '@/store/index.js'


// 白名单
const whiteList = [
	'/', // 注意入口页必须直接写 '/'
	'/pages/auth/login',
	'/pages/auth/otherlogin',
	'/pages/index/index',
	'/pages/car/detail',
	'/pages/pyq/index',
	'/pages/mine/mine',
	'/pages/shop/shop',
	'/pages/pyq/detail',
	'/pages/mine/vipPkg',
	'/pages/search/search',
	'/pages/search/plate',
	'/pages/auth/privacyagreement',
	'/pages/auth/vipprivacy',
	'/pages/mine/gzh'
]

export default async function() {
	const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']
	// 用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
	list.forEach(item => {
		uni.addInterceptor(item, {
			invoke(e) {
				// 获取要跳转的页面路径（url去掉"?"和"?"后的参数）
				const url = e.url.split('?')[0]
				// 判断当前窗口是白名单，如果是则不重定向路由
				let pass
				if (whiteList) {
					pass = whiteList.some(item => {
						if (typeof(item) === 'object' && item.pattern) {
							return item.pattern.test(url)
						}
						return url === item
					})
				}

				store.dispatch('user/reloadUser')
				// 不是白名单并且没有token 
				if (!pass && !getToken()) {
					uni.showModal({
						title: "温馨提醒",
						content: '马上登录',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({ url: '/pages/auth/login' })
							}
						}
					})
					return false
				}
				return e
			},
			fail(err) { // 失败回调拦截
				console.log(err)
			}
		})
	})
}